﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using System.ComponentModel;
using System.Net;
using System.IO;

namespace Vision.Core.ActivityComponents.IO.Http
{
	public class HttpDownloadFile : NativeActivity
	{
		/// <summary>
		/// Gets or sets the url of the file to download.
		/// </summary>
		[Category("Input")]
		public InArgument<string> Url { get; set; }

		/// <summary>
		/// Gets or sets the data of the file downloaded.
		/// </summary>
        [Category("Output")]
        public OutArgument<byte[]> Data { get; set; }

		/// <summary>
		/// 
		/// </summary>
		/// <param name="context"></param>
		protected override void Execute(NativeActivityContext context)
		{
			HttpWebRequest request = HttpWebRequest.Create(this.Url.Get(context)) as HttpWebRequest;
			WebResponse response = request.GetResponse();

			byte[] data = null;
			using (Stream responseStream = response.GetResponseStream())
			{
				data = readStream(responseStream);
			}

			this.Data.Set(context, data);
		}

		private byte[] readStream(Stream dataStream)
		{
			byte[] total_stream = new byte[0];
			byte[] stream_array = new byte[0];

			byte[] buffer = new byte[1024];
			int read = 0;

			while ((read = dataStream.Read(buffer, 0, buffer.Length)) > 0)
			{
				stream_array = new byte[total_stream.Length + read];
				total_stream.CopyTo(stream_array, 0);
				Array.Copy(buffer, 0, stream_array, total_stream.Length, read);
				total_stream = stream_array;
			}

			return total_stream;
		}
	}
}
